const EC = require('../comm/err-code');
const helper = require('../comm/api-helper');
const rCache = require('../model/redis_cache');
const HJSON = require('hjson');
const express = require('express');
const api = express();

// 返回所有策略型号信息
api.post('/get-all-types',async(req, resp) => {
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG, data:[]};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 获取信息
  let allTypeNodes = await rCache.keys(rCache.N_Ptype, 'all-types:*');
  for(node of allTypeNodes){
    let onePcy = await rCache.getAll(node);
    if (onePcy.level <= uInfo.level && (onePcy.display == 0 || onePcy.display == uInfo.uid)) {
      res.data.push(onePcy); // display及level匹配才显示给用户
    }
  }
  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;

  resp.json(res);
})

// 从redis缓存里读取指定的策略选项信息
api.post('/get-options',async(req, resp) => {
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG, data:[]};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  if (param.name) {
    let typeNode = await rCache.getKey(rCache.N_Ptype, param.name);
    let typeObj = HJSON.parse(typeNode);
    for (field of typeObj) {
      field.options = helper.OptionsLevelHandle(uInfo.level, field.options);
      field.options_e = helper.OptionsLevelHandle(uInfo.level, field.options_e);
      field.explain = helper.OptionsLevelHandle(uInfo.level, field.explain);
      res.data.push(field); // display及level匹配才显示给用户
    }
    res.code = EC.SUCESS;
    res.msg = EC.SUCESS_MSG;
  } else {
    res.code = EC.NOT_FOUNT;
    res.msg = EC.NOT_FOUNT_MSG;
  }

  resp.json(res);
})

module.exports = api;